﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using FrameWork.DataBaseProvider;
using System.Data.Common;
using Microsoft.Office.Interop.Word;
using Framework.Log;
using RFSerchComponent;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Threading;
namespace IndexService
{
    partial class RealTimeIndexesService : ServiceBase
    {
        public RealTimeIndexesService()
        {
            InitializeComponent();
        }
        //日志类
        private Framework.Log.ILog log = Framework.Log.LogFactory.CreateInstance();
        //   words.ApplicationClass wordApp;
        private double AlarmTimeSpan;
        private System.Timers.Timer realTimer;

        private void ParseConfig()
        {
            //get the config information from app.config
            this.AlarmTimeSpan = 1000 * double.Parse(ConfigurationSettings.AppSettings["AlarmTimeSpan"].ToString().Trim());
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                ParseConfig();
                log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "实时库启动！"));
                this.realTimer = new System.Timers.Timer(this.AlarmTimeSpan);
                this.realTimer.Enabled = true;
                this.realTimer.Elapsed += new System.Timers.ElapsedEventHandler(RealTimer_Elapsed);
                this.realTimer.Start();
            }
            catch (Exception ex)
            {
                log.WirteLog(ex.Message);
                log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "实时库被终止！"));
                this.realTimer.Close();
            }
        }

        protected override void OnStop()
        {
            try
            {
                log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "实时库停止！"));
                this.realTimer.Stop();
                this.realTimer.Enabled = false;
            }
            catch (Exception ex)
            {
                log.WirteLog(ex.Message);
                log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "实时库被终止！"));
            }
            finally
            {
                this.realTimer.Close();
            }
        }

        protected void RealTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string workTime = ConfigurationManager.AppSettings["WorkTime"];
            if (CheckTime(workTime))
            //if (true)
            {
                try
                {
                    this.realTimer.Stop();

                    log.WirteLog(string.Concat("\r\n", DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "操作开始...."));
                    log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库【构建xml数据开始】......"));

                    //判断实时库中，文件是否有isXML状态为1（准备创建索引的数据）
                    int dataCount = IndexCore.PreapareData(EnumServices.REAL_TIME_REBUILT);

                    //if (wordApp != null)//再关闭
                    //{
                    //    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                    //    wordApp = null;
                    //}


                    log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库【构建xml数据结束】,共构建数据数：", dataCount, "条"));

                    log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库【创建索引开始】......"));
                    //判断实时库中，文件是否有isXML状态为1（准备创建索引的数据）
                    //创建索引，创建完成一个，update一条记录的状态
                    string updateIndexSql = "";
                    int indexCount = 0;
                    if (dataCount <= 0)
                    {
                        log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库【创建索引结束（无新增数据）】"));
                        return;
                    }

                    updateIndexSql = IndexCore.CreateIndex(ref indexCount, EnumServices.REAL_TIME_REBUILT);
                    log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库【创建索引结束】,共更新记录数：", indexCount, "条"));

                    if (updateIndexSql != "")
                    {
                        bool result = false;
                        log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库更新isXML状态为2【更新数据库开始】......"));
                        result = new DbHelper(Const.REAL_TIME_DBCONNECTION).ExeMoreDB(updateIndexSql);
                        log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), " 实时库更新isXML状态为2【更新数据库结束】更新", result ? "成功" : "失败"));
                    }

                }
                catch (Exception ex)
                {
                    log.WirteLog(ex.Message);
                }
                finally
                {
                    log.WirteLog(string.Concat(DateTime.Now.ToString("【yyyy-MM-dd hh:mm:ss】"), "操作结束....\r\n"));
                    this.realTimer.Start();
                }
            }
        }

        private bool CheckTime(string workTime)
        {
            bool result = false;
            XmlDocument doc = new XmlDocument();
            string docPath = ConfigurationManager.AppSettings["WorkTimePath"];
            try
            {
                doc.Load(docPath);
                if ((SearchXml(doc, DateTime.Now.ToString("yyyy-MM-dd")) == null) && (DateTime.Now.Hour.ToString() == workTime))
                {
                    result = true;
                    StartNewJob(ref doc);
                    doc.Save(docPath);
                }
            }
            catch (Exception ex)
            {
                log.WirteLog(ex.Message);
            }
            return result;
            
        }

        /// <summary>
        /// 添加新的工作记录
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="id"></param>
        public void StartNewJob(ref XmlDocument doc)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                //写入日志文件
                XmlElement workRecord = doc.CreateElement("WorkRecord");
                XmlElement record = doc.CreateElement("record");
                XmlAttribute date = doc.CreateAttribute("date");
                date.Value = DateTime.Now.ToString("yyyy-MM-dd");
                XmlAttribute executeTime = doc.CreateAttribute("executeTime");
                executeTime.Value = DateTime.Now.ToString("HH:mm:ss");


                workRecord.AppendChild(record);
                record.Attributes.Append(date);
                record.Attributes.Append(executeTime);

                XmlNode root = doc.SelectSingleNode("WorkRecord");
                root.AppendChild(workRecord);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 寻找工作记录
        /// </summary>
        private XmlNode SearchXml(XmlDocument doc, string today)
        {
            XmlNode record = doc.SelectSingleNode(string.Format("//record[@date='{0}']", today));
            return record;
        }

     

    }



    
}
